#!/usr/bin/python3
# -*- coding:utf-8 -*-
# __author__ = '__Tony__'
import logging

from .common import session_begin
from sqlalchemy.orm import Session
from sqlalchemy import select
from app.yg_crm import orm, schemas
from typing import List
from sqlalchemy.orm import class_mapper
from log import log
from sqlalchemy.inspection import inspect


def create_template_type(db: Session, template_types: List[schemas.TemplateType]):

    t_arr = [orm.TemplateType(** template_type.model_dump(exclude_unset=True, exclude_none=True, exclude={'create_by', 'create_time'})) if template_type.id else
             orm.TemplateType(** template_type.model_dump(exclude_unset=True, exclude_none=True)) for template_type in template_types]

    for t in t_arr:
        if t.id:
            db.merge(t)
        else:
            db.add(t)

    #   db.refresh(t)
    db.commit()
    return t_arr


def create_template(db: Session, templates: List[schemas.Template]):
    t_arr = [orm.Template(** template.model_dump(exclude_unset=True, exclude_none=True, exclude={'create_by', 'create_time'})) if template.id
             else orm.Template(** template.model_dump(exclude_unset=True, exclude_none=True)) for template in templates]
    # db.add_all(t_arr)
    for t in t_arr:
        if t.id:
            db.merge(t)
        else:
            db.add(t)

    db.commit()
    return t_arr


@session_begin
def get_template_types(db: Session):
    res = db.query(orm.TemplateType).all()
    return res


# session 影响返回为空问题
@session_begin
def get_templates(db: Session):
    res = db.query(orm.Template).all()
    # 属性测试
    # print("Template:", type(res.__dict__['template_type'].__dict__))
    # print("Template_json:", res.to_dict())
    # log.info("class:{0}", class_mapper(orm.Template).columns)
    # log.info("class:{0}", inspect(orm.Template).columns)
    # log.info("class:{0}", [ a for a in orm.Template.__mapper__.attrs])
    # log.info("class:{0}", class_mapper(orm.Template).mapped_table.__dict__)
    return res


@session_begin
def get_templates_by_ids(db: Session, ids: List[int], is_delete: bool = False):
    # select(orm.Template).where(orm.Template.id.in_(ids))
    q = db.query(orm.Template).where(orm.Template.id.in_(ids))
    if is_delete:
        return q.delete()
    else:
        return q.all()

